package com.ysl.servlet;

import com.alibaba.fastjson.JSONObject;
import com.ysl.bean.Condition;
import com.ysl.bean.Education;
import com.ysl.bean.PageBean;
import com.ysl.bean.UserDemo;
import com.ysl.service.EducationService;
import com.ysl.service.EducationServiceImpl;
import com.ysl.service.UserService;
import com.ysl.service.UserServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet(name = "ServletMain", urlPatterns = "/ServletMain")
public class ServletMain extends HttpServlet {
    UserService userservice = new UserServiceImpl();
    EducationService educationService = new EducationServiceImpl();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String cmd = request.getParameter("cmd");
        if(cmd.equals("login")){
            try {
                login(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("main")){
            try {
                main(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("register")){
            register(request,response);
        }else if(cmd.equals("del")){
            try {
                del(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("dellogin")){
            try {
                dellogin(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("updateInfo")){
            try {
                updateInfo(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("update")){
            try {
                update(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("loginUI")){
            try {
                loginUI(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else if(cmd.equals("isuserName")){
            try {
                isuserName(request,response);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String username = request.getParameter("username");
        String userpwd = request.getParameter("userpwd");

        String codetext = request.getParameter("codeText");
        String code = (String) request.getSession().getAttribute("code");

        if (!codetext.equalsIgnoreCase(code)){
            request.setAttribute("msg","验证码错误");
            request.getRequestDispatcher("/page/login.jsp").forward(request,response);
            return;
        }

        boolean user = false;
        try {
            user = userservice.findUser(username, userpwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user){
            request.getSession().setAttribute("username",username);
            response.sendRedirect(request.getContextPath()+"/ServletMain?cmd=main");
        }else{
            response.sendRedirect(request.getContextPath()+"/page/login.jsp");
        }
    }
    public void loginUI(HttpServletRequest request, HttpServletResponse response)throws Exception{
        List<Education> educations = educationService.findEducationAll();
        request.getSession().setAttribute("Education",educations);
        response.sendRedirect(request.getContextPath()+"/page/login.jsp");
    }
    public void main(HttpServletRequest request, HttpServletResponse response) throws Exception{

        HttpSession session = request.getSession();
        String username = (String) session.getAttribute("username");
        if (username == null){
            response.getWriter().write("<h1>请先登录，五秒后自动跳转到登录页面</h1>");
            //refresh:响应头，便是几秒后自动跳转到url
            response.setHeader("refresh","5;url="+request.getContextPath()+"/ServletMain?cmd=loginUI");
            return;
        }
        System.out.println("成功登录！！！");

        Map<String, String[]> map = request.getParameterMap();
        Condition condition = new Condition();
        BeanUtils.populate(condition,map);

        request.setAttribute("Condition",condition);

        String p1 = request.getParameter("p");
        Integer p = 1;
        if(p1 != null && !p1.isEmpty()){

            p = Integer.valueOf(p1);
        }

        //问题： 如何把从数据库中查询出来的用户数据，显示到页面上？
        try {
            PageBean pageBean = userservice.findUsers(condition,p);
            request.setAttribute("pageBean",pageBean);
            request.getRequestDispatcher("/page/main.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void register(HttpServletRequest request, HttpServletResponse response){
        Map<String, String[]> maps = request.getParameterMap();
        UserDemo userDemo = new UserDemo();

        System.out.println("maps = " + maps);

        //从前端传递的日期是String格式，但是实体中是Date类型，不能直接转换
        //使用日期转换器，来转换日期格式
        DateConverter dc = new DateConverter();
        //设置转换格式
        dc.setPatterns(new String[]{"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"});
        //实现注册转换
        ConvertUtils.register(dc, Date.class);

        try {
            BeanUtils.populate(userDemo,maps);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        String[] chks = request.getParameterValues("chk");
        userDemo.setChk(Arrays.toString(chks));

        try {
            boolean b = userservice.addUser(userDemo);
            if (b){
                response.getWriter().write("<h1>注册成功，五秒后自动跳转到登录页面</h1>");
                //refresh:响应头，便是几秒后自动跳转到url
                response.setHeader("refresh","5;url="+request.getContextPath()+"/ServletMain?cmd=loginUI");
            }else {
                response.sendRedirect(request.getContextPath()+"/page/error.jsp");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void del(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String id = request.getParameter("id");
        try {
            boolean b = userservice.delUser(Integer.parseInt(id));
            response.sendRedirect(request.getContextPath()+"/ServletMain?cmd=main");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void dellogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession(false);
        if (session != null){
            session.removeAttribute("username");
        }
        response.sendRedirect(request.getContextPath()+"/page/login.jsp");
    }
    public void updateInfo(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String id = request.getParameter("id");
        UserDemo user = userservice.findUserId(Integer.parseInt(id));
        request.setAttribute("user",user);
        request.getRequestDispatcher("/page/update.jsp").forward(request,response);
    }
    public void update(HttpServletRequest request, HttpServletResponse response) throws Exception{
        Map<String, String[]> maps = request.getParameterMap();
        UserDemo userDemo = new UserDemo();

        //从前端传递的日期是String格式，但是实体中是Date类型，不能直接转换
        //使用日期转换器，来转换日期格式
        DateConverter dc = new DateConverter();
        //设置转换格式
        dc.setPatterns(new String[]{"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"});
        //实现注册转换
        ConvertUtils.register(dc, Date.class);

        try {
            BeanUtils.populate(userDemo,maps);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        String[] chks = request.getParameterValues("chk");
        userDemo.setChk(Arrays.toString(chks));
        System.out.println("userDemo = " + userDemo);

        boolean modif = userservice.modif(userDemo);
        if (modif){
            main(request,response);
        }else {
            response.sendRedirect(request.getContextPath()+"/page/error.jsp");
        }
    }
    public void isuserName(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String username = request.getParameter("username");
        System.out.println("username = " + username);

        boolean b = userservice.findUsername(username);
        JSONObject json = new JSONObject();
        if (b){
            json.put("msg","yes");
//            response.getWriter().write("{\"msg\":\"yes\"}");
        }else{
            json.put("msg","no");
//            response.getWriter().write("{\"msg\":\"no\"}");
        }
        response.getWriter().write(json.toJSONString());
    }
}
